const puppeteer = require('puppeteer');
const fetch = require('node-fetch');
const configOption = require('../config/config');
const { setFile, readFile } = require('./xlsx');
// 订阅标识
let publish_system_sess_ = '';
let timing = null;
// 订阅对象信息
global.subscribeObj = {}


module.exports = {
  /**
   * @param {Object} options  同步配置信息  
   * @param options.importType {number} 导出方式 1追加导入 2覆盖导入
   */
  async getChanDaoData(options) {
    const browser = await puppeteer.launch({
      headless: true,
      defaultViewport: null,
      // chrome://version/ 获取浏览器数据目录
      // userDataDir:'C:\Users\22693\AppData\Local\Temp\puppeteer_dev_chrome_profile-5QqrUy\Default',
      args: [
        // 解除浏览器禁止跨域访问的限制
        '--disable-web-security --user-data-dir',
      ],
    });

    const page = await browser.newPage();
    const cookie0 = {
      name: "zentaosid",
      value: options.zentaosid,
      domin: configOption.baseConfig.domin,
      path: configOption.baseConfig.path,
      url: configOption.baseConfig.url,
    };
    const cookie1 = {
      name: "pagerMyTask",
      value: "2000",
      domin: configOption.baseConfig.domin,
      path: configOption.baseConfig.path,
      url: configOption.baseConfig.url,
    };

    await page.setCookie(cookie0, cookie1);
    const myTaskData = await waitFrameMyTashForm(page);
    const researchData = await waitFrameResearchForm(page);
    const bugData = await waitFrameBug(page);
    setXlsx([...bugData.allData,...myTaskData.allData, ...researchData.allData], options)
  },
  async watchPublicInfo(option){
    if(global.subscribeObj[option.packageId]){
      return []
    }
    publish_system_sess_ = option.publish_system_sess_
    getTask().then(async (response) => {
        const data = await response.json()
        const list = data.d.tasks
        if(!list)
          return
        const findItem = list.find(item => item.id == option.packageId)
        if(findItem){
          global.subscribeObj[option.packageId] = {...findItem }
          if(timing){
            clearInterval(timing)
          }
          timingFn()
          timing = setInterval(timingFn,15000)
        }
    })
    // await page.goto(configOption.baseUrlPublishSystemWatchPage)
    
    function timingFn() {
      const keyList = Object.keys(global.subscribeObj)
      console.log(keyList.length,global.subscribeObj)
      if(publish_system_sess_ && keyList.length > 0){
        console.log("start")
        getTask().then(async (response) => {
          const data = await response.json()
          const list = data.d.tasks
          keyList.forEach((key)=>{
            if(!list)
              return
            const findItem = list.find(item => item.id === key)
            option.event.sender.send("watchPublicInfoUpdate",{
              list
            })
            if(!findItem){
              // 通知消息
              option.event.sender.send("watchPublicInfoUpdate",{
                list
              })
              option.event.sender.send("watchPublicInfoTip",{
                successObj:{...subscribeObj[key]}
              })
              delete global.subscribeObj[key]
            }
          })
        })
      }
    }
  }
}
/**
 * 获取我的任务第一个表数据
 * @param {Object} frame iframe标签
 * @returns 数据
 */
async function getMyTaskOnePageData(frame) {
  const data = await frame.$$eval('#myTaskList > tr > td.c-name > a',
    el => el.map(e => {
      return {
        href: e.href,
        name: e.innerHTML
      }
    })
  )
  return data.map(e => {
    return {
      href: e.href,
      name: `【需求】${e.name}`
    }
  })
}

/**
 * 获取研发需求数据
 * @param {Object} frame iframe标签
 * @returns 数据
 */
async function getResearchOnePageData(frame) {
  const data = await frame.$$eval('#storyList > tbody > tr > td.c-name.nobr > a',
    el => el.map(e => {
      return {
        href: e.href,
        name: e.innerHTML
      }
    })
  )
  return data.map(e => {
    return {
      href: e.href,
      name: `【需求】${e.name}`
    }
  })
}

/**
 * 获取我的bug数据
 * @param {Object} frame iframe标签
 * @returns 数据
 */
async function getBugOnePageData(frame) {
  const data = await frame.$$eval('#bugList > tbody > tr > td:nth-child(2) > a',
    el => el.map(e => {
      return {
        href: e.href,
        name: e.innerHTML
      }
    })
  )
  return data.map(e => {
    return {
      href: e.href,
      name: `【BUG】${e.name}`
    }
  })
}

/**
 * 等待页面切换完毕
 * @param {object} frame iframe对象
 * @param {number} page 等到指定数量
 * @returns 
 */
// async function waitLoadingSuccess(frame, page) {
//   while (true) {
//     await new Promise(resolve => setTimeout(resolve, 100));
//     const nowPage = await frame.waitForSelector('#myTaskForm > div.table-footer > ul > li:nth-child(5) > div > strong:nth-child(1)');
//     const nowPageNum = await nowPage.evaluate(el => el.textContent);
//     await frame.waitForSelector('#myTaskList > tr > td.c-name > a')
//     if (nowPageNum == page) return Promise.resolve();
//   }
// }
async function waitFrameMyTashForm(page) {
  await page.goto(configOption.baseUrlMyTash);
  await page.screenshot({ path: 'example.png' });
  const frameMy = await page.waitForSelector('#appIframe-my');
  const frame = await frameMy.contentFrame();
  // const frameMyMainContent = await frame.waitForSelector('#myTaskForm > div.table-footer.fixed-footer > ul > li:nth-child(1) > div > strong');
  // 任务数量
  // const myMainContentNum = await frameMyMainContent.evaluate(el => el.textContent)
  // 页数
  // const myMainContentPage = Math.ceil(myMainContentNum / configOption.pageSize)
  let allData = []
  const getData = await getMyTaskOnePageData(frame)
  allData = [...allData, ...getData]
  return {
    allData
  }
}

async function waitFrameBug(page) {
  await page.goto(configOption.baseUrlBug);
  await page.screenshot({ path: 'example1.png' });
  const frameMy = await page.waitForSelector('#appIframe-my');
  const frame = await frameMy.contentFrame();
  let allData = []
  const getData = await getBugOnePageData(frame)
  allData = [...allData, ...getData]
  return {
    allData
  }
}

async function waitFrameResearchForm(page) {
  await page.goto(configOption.baseUrlResearchForm);
  await page.screenshot({ path: 'example2.png' });
  const frameMy = await page.waitForSelector('#appIframe-my');
  const frame = await frameMy.contentFrame();
  let allData = []
  const getData = await getResearchOnePageData(frame)
  allData = [...allData, ...getData]
  return {
    allData
  }
}

/**
 * 
 * @param {Array} data 所有数据
 */
async function setXlsx(data, options) {
  const { mode } = options;
  let mapData;
  switch (mode) {
    case '1':
      mapData = appendImport(data)
      break;
    case '2':
      mapData = overWriteImport(data)
      break;
    case '3':
      mapData = differenceImport(data)
      break;
  }
  setFile(mapData)
}

function getDateInfo() {
  const baseDate = new Date()
  const baseId = Date.parse(baseDate)
  const nowDate = `${baseDate.getFullYear()}/${(0 + String(baseDate.getMonth() + 1)).slice(-2)}/${(0 + String(baseDate.getDate())).slice(-2)}`
  return { baseId, nowDate }
}

function appendImport(data) {
  let returnData = data;
  const baseData = readFile()[0].data;
  returnData = returnData.filter((item) => {
    if (baseData.find((baseItem) => baseItem[1] === item.href)) {
      return false;
    }
    return true;
  })
  const { baseId, nowDate } = getDateInfo();
  returnData = returnData.map((item, index) => {
    return [item.name, item.href, nowDate, "", String(baseId + index), true]
  })
  return [...baseData, ...returnData]
}

function overWriteImport(data) {
  const { baseId, nowDate } = getDateInfo();
  return data.map((item, index) => {
    return [item.name, item.href, nowDate, "", String(baseId + index), true]
  })
}

function differenceImport(data) {
  let returnData = [...data];
  let baseData = readFile()[0].data;
  returnData = returnData.filter((item) => {
    if (baseData.find((baseItem) => baseItem[1] === item.href)) {
      return false;
    }
    return true;
  })
  baseData = baseData.filter((item) => {
    if (!data.find(baseItem => baseItem.href === item[1]) && !item[3]) {
      return false;
    }
    return true;
  })
  const { baseId, nowDate } = getDateInfo();
  returnData = returnData.map((item, index) => {
    return [item.name, item.href, nowDate, "", String(baseId + index), true]
  })
  return [...baseData, ...returnData]
}

async function getTask(){
  return new Promise((resolve, reject) => {
    fetch(configOption.baseUrlPublishSystemWatchPage, {
      "headers": {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9",
        "sec-ch-ua": "\".Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"103\", \"Chromium\";v=\"103\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "cookie": `publish_system_sess_=${publish_system_sess_}`,
        "Referer": configOption.baseUrlPublishSystemWatchPage,
        "Referrer-Policy": "strict-origin-when-cross-origin"
      },
      "body": null,
      "method": "GET"
    }).then(res => {
      resolve(res)
    }).catch(rej =>{
      reject(rej)
    })
  })
}
